package com.lw.leetcode.linked.b;

import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * 1670. 设计前中后队列
 *
 * @author liw
 * @version 1.0
 * @date 2022/6/25 22:30
 */
public class FrontMiddleBackQueue {

    private LinkedList<Integer> as;
    private LinkedList<Integer> bs;

    public FrontMiddleBackQueue() {
        as = new LinkedList<>();
        bs = new LinkedList<>();
    }

    public void pushFront(int val) {
        as.addFirst(val);
        if (as.size() > bs.size()) {
            bs.addFirst(as.pollLast());
        }
    }

    public void pushMiddle(int val) {
        if (as.size() == bs.size()) {
            bs.addFirst(val);
        } else {
            as.addLast(val);
        }
    }

    public void pushBack(int val) {
        bs.addLast(val);
        if (bs.size()- 1 > as.size()) {
            as.addLast(bs.pollFirst());
        }
    }

    public int popFront() {
        if (as.isEmpty()) {
            if (bs.isEmpty()) {
                return -1;
            }
            return bs.pollLast();
        }
        int v = as.pollFirst();
        if (bs.size()- 1 > as.size()) {
            as.addLast(bs.pollFirst());
        }
        return v;
    }

    public int popMiddle() {
        if (as.isEmpty()) {
            if (bs.isEmpty()) {
                return -1;
            }
            return bs.pollFirst();
        }
        if (as.size() >= bs.size()) {
            return as.pollLast();
        }
        return bs.pollFirst();
    }

    public int popBack() {
        if (bs.isEmpty()) {
            if (as.isEmpty()) {
                return -1;
            }
            return as.pollLast();
        }
        int v = bs.pollLast();
        if (as.size() > bs.size()) {
            bs.addFirst(as.pollLast());
        }
        return v;
    }

}
